package thttp

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"gitee.com/man0sions/IdCreator/core"
	"log"
	"net/http"
	"time"
)

var (
	HttpServer *http.Server
)
type RouterFunc func(...gin.HandlerFunc) *gin.Engine
func NewHttpServer(Vp *viper.Viper,routerFunc RouterFunc) (engine *gin.Engine) {
	gin.DefaultWriter = core.GLog.InfoWriter
	gin.DefaultErrorWriter = core.GLog.ErrorWriter
	gin.SetMode(Vp.GetString("debug"))
	engine = routerFunc()
	HttpServer = &http.Server{
		Addr:         ":" + Vp.GetString("httpServer.port"),
		Handler:      engine,
		ReadTimeout:  time.Duration(Vp.GetInt("httpServer.ReadTimeout")) * time.Millisecond,
		WriteTimeout: time.Duration(Vp.GetInt("httpServer.WriteTimeout")) * time.Millisecond,
		ErrorLog:     log.New(core.GLog.ErrorWriter, "E", log.Lshortfile),
	}
	go func() {
		log.Println("http listen on:" + Vp.GetString("httpServer.port"))
		if err := HttpServer.ListenAndServe(); err != nil {
			log.Panicln(err)
		}
	}()

	return
}

func StopHttpServer() {
	ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
	defer cancel()
	if err := HttpServer.Shutdown(ctx); err != nil {
		log.Panicln(err)
	}
	log.Println("http stopped")
}
